<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

use App\Models\Imgs as Info;

class Imgs extends Controller
{
    protected $typeId;

    function __construct(Request $request)
    {
        $type = $request->type;

        $this->typeId = $this->typeToId($type);
    }

    public function new(Request $request)
    {
        Info::create([
            'type' => $this->typeId,
            'img_url' => $request->img_url,
        ]);

        return $this->code(200);
    }

    public function get()
    {
        return Info::select('id', 'number', 'img_url', 'title', 'is_show')->whereType($this->typeId)->latest('number')->get();
    }

    public function put(Request $request)
    {
        $id = $request->id;
        $info = Info::find($id);

        $name = $request->name;
        $value = $request->value;

        if ($name == 'delete') {
            $info->delete();
        } else {
            $info->$name = $value;
            $info->save();
        }

        return $this->code(200);
    }

    public function upimg(Request $request) {
        $img = $request->file('img');

        if (!$img->isValid()) {
            return $this->code(201);
        } else {

            // if (App()->environment() == 'local') {
            //     // 本地保存
            //     $path = $img->store('imgs/');
            //     $url = Storage::url($path);
                
            // } else {
            //     // 云端保存
            //     $path = $img->store('imgs/', 'qiniu');
            //     $url = Storage::disk('qiniu')->url($path);
            // }
            
            // 本地保存
            $path = $img->store('imgs/');
            $url = Storage::url($path);

            return $this->code(200, $url, 'url');
        }
    }
}
